<?php

class UserController extends Controller{
	
	/**
	 * @param int cid 分类id，0代表所有图书
	 */
	public function actionHome($cid = 0,$pageno = 1){
		if(User::id() === 0){
			$this->render('user/login.tpl');
		}
		$ret = UserService::home($cid,$pageno);
		$this->render('user/home.tpl',$ret);
	}
	
	public function actionDump($bookId){
		$ret = UserService::dumpBook($bookId);
		$this->renderJson($ret);
	}
	
	/**
	 * e_type=1:本书无法下载
	 * e_type=2:本书未完结
	 * e_type=3 :本图书和书名不符
	 */
	public function actionSuggest(){
		$type = Param::getInt('e_type');
		$bookId = Param::getInt('book_id');
		$suggestInfo = BookService::suggest($bookId,$type);
		$this->render('book/suggest.tpl',$suggestInfo);
	}
	
	public function actionErrorReport(){
		$bookId = Param::getInt('id');
		$eType = Param::getInt('etype');
		$desn = Param::getStr('desn');
		echo BookErrorAR::saveBookError(User::id(),User::name(),$bookId,$eType,MyUtil::getRemoteAddr(),$desn);
	}
	
	public function actionEditbook($id = 0){
		$priBookInfo = BookService::privateBookInfo($id);
		$pubBookInfo = BookService::publicBookInfo($id);
		$categorys = CategoryService::getAllCategorys();
		$data = array('pri'=>$priBookInfo,'pub'=>$pubBookInfo,'cs'=>$categorys);
		$this->render('book/user_edit.tpl',$data);
	}
	
	public function actionDoEditBook(){
		$bookId = Param::getInt('book_id');
		$selectedCid = Param::getInt('selected_cid');
		$priBookName = Param::getStr('priBookName');
		$pubBookName = Param::getStr('pubBookName');
    	$author = Param::getStr('pubAuthor');
    	$bookDesn = Param::getStr('book_desn');
    	
    	BookService::userUpdateBook($bookId,$selectedCid,$priBookName,$pubBookName,$author,$bookDesn);
    	$this->redirect('/user/home');
	}
	
	public function actionDelbook($id = 0){
		UserService::delBook($id);
		$this->redirect('/user/home');
	}
	
    public function actionUserName(){
        echo User::name();
    }
    
    public function actionSignin(){
    	$genSize = UserService::whenLogin(User::id(),User::name());
    	echo $genSize;
    }

    public function actionUsernameExists(){
        $username = trim($_REQUEST['username']);
        if($username == ''){
            echo 1;
            exit;
        }
        $cnt = UserService::usernameExists($username);
        echo $cnt == 0 ? 0 : 1;
    }

    public function actionEmailExists(){
        $email = trim($_REQUEST['email']);
        if($email == ''){
            echo 1;
            exit;
        }
        $cnt = UserService::emailExists($email);
        echo $cnt == 0 ? 0 : 1;
    }
}
